﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BaLs.Models;
using MvcPaging;
using System.Data.Linq;

namespace BaLs.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {

        private const int defaultPageSize = 10;
        private IList<Link> publicLinks = new List<Link>();
        
        //public ActionResult Index()
        //{
        //    ViewData["Message"] = "Latest links";
        //    BaLsRespository res = new BaLsRespository();
        //    return View(res.GetAllPublicLink());    
        //}

      public ActionResult Index(int? page)
		{
            BaLsRespository res = new BaLsRespository();
            publicLinks = res.GetAllPublicLink().ToList<Link>();            
			int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
			return View(this.publicLinks.ToPagedList(currentPageIndex, defaultPageSize));
		}

      public ActionResult Search(String searchTag, int? page)
      {
          if (searchTag != null)
              Session["searchTag"] = searchTag;

          EntitySet<Tag> tags = getTags(Session["searchTag"].ToString());
          BaLsRespository res = new BaLsRespository();

          ViewData["searchTag"] = Session["searchTag"].ToString();
          
          publicLinks = res.GetLinkByTags(tags).ToList<Link>();
          int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
          return View("Index", this.publicLinks.ToPagedList(currentPageIndex, defaultPageSize));          
      }
        public ActionResult About()
        {
            return View();
        }

        private EntitySet<Tag> getTags(string strTag)
        {
            EntitySet<Tag> tagSet = new EntitySet<Tag>();
            Tag tagItem;
            string[] str = strTag.Split();
            foreach (string tag in str)
            {
                tagItem = new Tag();
                tagItem.tag_desc = tag;
                tagSet.Add(tagItem);
            }
            return tagSet;
        }
    }
}
